# -*- coding: utf-8 -*-

from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from sprManager.views import reqUser
from sprManager.models import News
from sprManager.forms import AddNews
import datetime

@login_required
def mainPage(request):
    dataProfil=reqUser(request)
    if dataProfil.isNauczyciel:
        newsy=News.objects.filter(nauczyciel=dataProfil)
        if request.method=='POST':
            form=AddNews(request.POST)
            if form.is_valid():
                form=form.cleaned_data
                
                data=News()
                data.title=form['tytul']
                data.tresc=form['tresc']
                data.grupa=form['grupa']
                data.data=datetime.datetime.now()
                data.nauczyciel=dataProfil
                data.save()
                
                return render_to_response("home.html", {'newsy':newsy,'message':'Dodano news.', 'user':request.user},
                               context_instance=RequestContext(request))
            else:
               return render_to_response("home.html", {'newsy':newsy, 'message':'Dane w formularzu nie są poprawne.','form':form,'user':request.user},
                               context_instance=RequestContext(request)) 
        else:
            form=AddNews()
            return render_to_response("home.html", {'newsy':newsy, 'form':form, 'user':request.user},
                               context_instance=RequestContext(request))
    else:
        newsy=News.objects.filter(grupa=dataProfil.team)
        return render_to_response("home.html", {'newsy':newsy, 'dataProfil':dataProfil, 'user':request.user},
                               context_instance=RequestContext(request))
